<template>
  <div class="page-container">
    <ShipVerticalTabNav />
    
    <div class="list-page">
      <!-- 搜索和操作区域 -->
      <div class="filter-area">
        <div class="search-area">
          <el-input
            v-model="searchValue"
            placeholder="请输入船舶名称搜索"
            clearable
            class="search-input"
            @keyup.enter="handleSearch"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </div>
        <div class="operation-area">
          <el-button class="custom-button primary-button" @click="handleAdd">
            <el-icon><Plus /></el-icon>新增船舶
          </el-button>
        </div>
      </div>

      <!-- 表格区域 -->
      <el-table
        v-loading="loading"
        :data="tableData"
        border
        style="width: 100%"
        height="calc(100vh - 250px)"
        :header-cell-style="{ background: 'var(--el-bg-color-page)' }"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column label="序号" type="index" width="80" align="center" />
        <el-table-column label="中文船名" prop="nameCn" min-width="120" />
        <el-table-column label="英文船名" prop="nameEn" min-width="120" />
        <el-table-column label="船舶类型" prop="shipType" width="120" align="center" />
        <el-table-column label="MMSI号" prop="mmsi" width="120" align="center" />
        <el-table-column label="IMO号" prop="imo" width="120" align="center" />
        <el-table-column label="呼号" prop="callSign" width="100" align="center" />
        <el-table-column label="国籍" prop="nationality" width="100" align="center" />
        <el-table-column label="船长(米)" prop="length" width="100" align="center" />
        <el-table-column label="船宽(米)" prop="beam" width="100" align="center" />
        <el-table-column label="建成日期" prop="buildDate" width="120" align="center">
          <template #default="scope">
            {{ formatDate(scope.row.buildDate) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="300" fixed="right" align="center">
          <template #default="scope">
            <el-button link type="primary" @click="navigateToRadar(scope.row)">
              雷达扫描
            </el-button>
            <el-button link type="success" @click="navigateToAIS(scope.row)">
              AIS数据
            </el-button>
            <el-button type="primary" link @click="handleEdit(scope.row)">编辑</el-button>
            <el-button type="danger" link @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 30, 50]"
          :background="true"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>

      <!-- 编辑/新增弹窗 -->
      <el-dialog
        v-model="dialogVisible"
        :title="dialogType === 'add' ? '新增船舶' : '编辑船舶'"
        width="60%"
        destroy-on-close
      >
        <el-form
          ref="formRef"
          :model="form"
          :rules="rules"
          label-width="120px"
          class="dialog-form"
        >
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="中文船名" prop="nameCn">
                <el-input v-model="form.nameCn" placeholder="请输入中文船名" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="英文船名" prop="nameEn">
                <el-input v-model="form.nameEn" placeholder="请输入英文船名" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="MMSI号" prop="mmsi">
                <el-input v-model="form.mmsi" maxlength="9" placeholder="请输入9位MMSI号" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="IMO号" prop="imo">
                <el-input v-model="form.imo" maxlength="7" placeholder="请输入7位IMO号" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="呼号" prop="callSign">
                <el-input v-model="form.callSign" placeholder="请输入呼号" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="国籍" prop="nationality">
                <el-input v-model="form.nationality" placeholder="请输入国籍" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="船舶所有人" prop="owner">
                <el-input v-model="form.owner" placeholder="请输入船舶所有人" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="造船厂" prop="shipyard">
                <el-input v-model="form.shipyard" placeholder="请输入造船厂" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="船舶类型" prop="shipType">
                <el-select v-model="form.shipType" placeholder="请选择船舶类型" style="width: 100%">
                  <el-option label="货船" value="货船" />
                  <el-option label="客船" value="客船" />
                  <el-option label="渔船" value="渔船" />
                  <el-option label="油轮" value="油轮" />
                  <el-option label="集装箱船" value="集装箱船" />
                  <el-option label="其他" value="其他" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="船籍港" prop="portRegistry">
                <el-input v-model="form.portRegistry" placeholder="请输入船籍港" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="船长(米)" prop="length">
                <el-input-number v-model="form.length" :precision="2" :min="0" style="width: 100%" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="船宽(米)" prop="beam">
                <el-input-number v-model="form.beam" :precision="2" :min="0" style="width: 100%" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="型深(米)" prop="depth">
                <el-input-number v-model="form.depth" :precision="2" :min="0" style="width: 100%" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="型宽(米)" prop="mouldedBeam">
                <el-input-number v-model="form.mouldedBeam" :precision="2" :min="0" style="width: 100%" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="总吨(吨)" prop="gross">
                <el-input-number v-model="form.gross" :precision="2" :min="0" style="width: 100%" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="净吨(吨)" prop="net">
                <el-input-number v-model="form.net" :precision="2" :min="0" style="width: 100%" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="最小干舷" prop="minFreeboard">
                <el-input-number v-model="form.minFreeboard" :precision="2" :min="0" style="width: 100%" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="建成日期" prop="buildDate">
                <el-date-picker
                  v-model="form.buildDate"
                  type="date"
                  placeholder="选择建造日期"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <template #footer>
          <span>
            <el-button @click="dialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="handleSubmit">确 定</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { Search, Plus } from "@element-plus/icons-vue";
import dayjs from "dayjs";
import { useRouter } from "vue-router";
import { 
  getShipInfoList, 
  getShipInfoById, 
  addShipInfo, 
  updateShipInfo, 
  deleteShipInfo 
} from "@/api/bridge/bisc/ship";
import ShipVerticalTabNav from '@/views/Bridge/basic-data/components/ShipVerticalTabNav.vue';

// 路由器
const router = useRouter();

// 表格数据
const tableData = ref([]);
const loading = ref(false);
const total = ref(0);
const currentPage = ref(1);
const pageSize = ref(10);
const searchValue = ref("");

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  nameCn: "",
});

// 弹窗控制
const dialogVisible = ref(false);
const dialogType = ref<"add" | "edit">("add");

// 表单数据
const formRef = ref();
const form = ref({
  id: "",
  nameCn: "",
  nameEn: "",
  mmsi: "",
  imo: "",
  callSign: "",
  nationality: "",
  owner: "",
  shipyard: "",
  shipType: "",
  portRegistry: "",
  length: 0,
  beam: 0,
  depth: 0,
  mouldedBeam: 0,
  gross: 0,
  net: 0,
  minFreeboard: 0,
  buildDate: "",
});

// 表单校验规则
const rules = {
  nameCn: [{ required: true, message: "请输入中文船名", trigger: "blur" }],
  shipType: [{ required: true, message: "请选择船舶类型", trigger: "change" }],
  mmsi: [
    { required: true, message: "请输入MMSI号", trigger: "blur" },
    { pattern: /^\d{9}$/, message: "MMSI号必须为9位数字", trigger: "blur" }
  ],
  imo: [
    { required: true, message: "请输入IMO号", trigger: "blur" },
    { pattern: /^\d{7}$/, message: "IMO号必须为7位数字", trigger: "blur" }
  ],
  length: [{ required: true, message: "请输入船长", trigger: "blur" }],
  beam: [{ required: true, message: "请输入船宽", trigger: "blur" }],
};

// 格式化日期
const formatDate = (date: string | number | Date) => {
  if (!date) return "-";
  return dayjs(date).format("YYYY-MM-DD");
};

// 获取列表数据
const getList = async () => {
  loading.value = true;
  try {
    queryParams.pageNum = currentPage.value;
    queryParams.pageSize = pageSize.value;
    queryParams.nameCn = searchValue.value;

    const res = await getShipInfoList(queryParams);
    tableData.value = res.rows || [];
    total.value = res.total || 0;
  } catch (error) {
    console.error("获取船舶列表失败:", error);
    ElMessage.error("获取船舶列表失败");
  } finally {
    loading.value = false;
  }
};

// 处理分页
const handleSizeChange = (val: number) => {
  pageSize.value = val;
  getList();
};

const handleCurrentChange = (val: number) => {
  currentPage.value = val;
  getList();
};

// 搜索
const handleSearch = () => {
  currentPage.value = 1;
  getList();
};

// 新增
const handleAdd = () => {
  dialogType.value = "add";
  form.value = {
    id: "",
    nameCn: "",
    nameEn: "",
    mmsi: "",
    imo: "",
    callSign: "",
    nationality: "",
    owner: "",
    shipyard: "",
    shipType: "",
    portRegistry: "",
    length: 0,
    beam: 0,
    depth: 0,
    mouldedBeam: 0,
    gross: 0,
    net: 0,
    minFreeboard: 0,
    buildDate: "",
  };
  dialogVisible.value = true;
};

// 编辑
const handleEdit = async (row: any) => {
  try {
    loading.value = true;
    const res = await getShipInfoById(row.id);
    dialogType.value = "edit";
    form.value = res.data;
    dialogVisible.value = true;
  } catch (error) {
    console.error("获取船舶详情失败:", error);
    ElMessage.error("获取船舶详情失败");
  } finally {
    loading.value = false;
  }
};

// 删除
const handleDelete = (row: any) => {
  ElMessageBox.confirm("确认删除该船舶信息吗？", "警告", {
    type: "warning",
  })
    .then(async () => {
      try {
        await deleteShipInfo(row.id);
        ElMessage.success("删除成功");
        getList();
      } catch (error) {
        console.error("删除船舶失败:", error);
        ElMessage.error("删除船舶失败");
      }
    })
    .catch(() => {});
};

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return;
  await formRef.value.validate(async (valid: boolean) => {
    if (valid) {
      try {
        if (dialogType.value === "add") {
          await addShipInfo(form.value);
          ElMessage.success("新增成功");
        } else {
          await updateShipInfo(form.value);
          ElMessage.success("修改成功");
        }
        dialogVisible.value = false;
        getList();
      } catch (error) {
        console.error("操作失败:", error);
        ElMessage.error("操作失败");
      }
    }
  });
};

// 导航到雷达扫描页面
const navigateToRadar = (row: any) => {
  router.push({ 
    path: '/basic-data/ship-radar', 
    query: { shipId: row.id, shipName: row.nameCn } 
  });
};

// 导航到AIS数据页面
const navigateToAIS = (row: any) => {
  router.push({ 
    path: '/basic-data/ship-ais', 
    query: { shipId: row.id, shipName: row.nameCn } 
  });
};

onMounted(() => {
  getList();
});
</script>

<style scoped lang="scss">
.page-container {
  display: flex;
  height: 100%;
  background: var(--el-bg-color-page);
  border-radius: 4px;
  box-shadow: var(--el-box-shadow-light);
  overflow: hidden;
}

.list-page {
  flex: 1;
  padding: 20px;
  overflow: auto;
}

.filter-area {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  background: var(--el-bg-color-overlay);
  padding: 16px;
  border-radius: 4px;

  .search-input {
    width: 300px;
  }
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.operation-area {
  display: flex;
  gap: 12px;

  .custom-button {
    position: relative;
    overflow: hidden;
    transition: all 0.3s ease;

    &::before {
      content: "";
      position: absolute;
      top: 50%;
      left: 50%;
      width: 0;
      height: 0;
      background: rgba(255, 255, 255, 0.2);
      border-radius: 50%;
      transform: translate(-50%, -50%);
      transition: width 0.6s ease, height 0.6s ease;
    }

    &:hover {
      transform: translateY(-2px);
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);

      &::before {
        width: 300px;
        height: 300px;
      }
    }

    &:active {
      transform: translateY(1px);
    }
  }

  .primary-button {
    background: var(--el-color-primary);
    border-color: var(--el-color-primary);
    color: white;

    &:hover {
      background: var(--el-color-primary-light-3);
      border-color: var(--el-color-primary-light-3);
    }
  }
}
</style>
